package com.smartcruise.task.nodeTaskDataEdit;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.dialog.widget.NormalListDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.smartcruise.R;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.data.cruiseData.NodeTaskListBean;
import com.smartcruise.report.AudioAdapter;
import com.smartcruise.report.AudioRecordActivity;
import com.smartcruise.report.EditType;
import com.smartcruise.report.ImageAdapter;
import com.smartcruise.report.VideoAdapter;
import com.smartcruise.util.FileUtils;
import com.smartcruise.util.IntentUtils;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.network.NodeUpload;
import com.smartcruise.util.network.OssManager;
import com.smartcruise.util.network.callBack.BaseCallBack;
import com.smartcruise.util.network.callBack.SimpleCallBack;
import com.smartcruise.util.network.netUtils.NetStatusUtils;
import com.smartcruise.util.network.netUtils.Result;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/1/25 0025
 */

public class NodeTaskDataEditPresenterImp implements NodeTaskDataEditContract.Presenter {

    private NodeTaskDataEditContract.View mView;
    private EditType editType;

    private ArrayList<String> audioList = new ArrayList<>();
    private ArrayList<String> imageList = new ArrayList<>();
    private ArrayList<String> videoList = new ArrayList<>();
    private AudioAdapter audioAdapter;
    private ImageAdapter imageAdapter;
    private VideoAdapter videoAdapter;
    private String currentImagePath, currentVideoPath;
    private boolean modify;
    private CruiseData cruiseData;
    private NodeTaskListBean nodeTaskListBean;
    private boolean isNetDataChanged;

    public NodeTaskDataEditPresenterImp(NodeTaskDataEditContract.View mView, EditType editType,
                                        CruiseData cruiseData, NodeTaskListBean nodeTaskListBean) {
        this.mView = mView;
        this.editType = editType;
        this.cruiseData = cruiseData;
        this.nodeTaskListBean = nodeTaskListBean;
        modify = editType != EditType.VIEW;
    }

    @Override
    public void start() {
        initData();
        audioAdapter = new AudioAdapter(getActivity(), R.layout.item_audio, audioList, this);
        audioAdapter.setModify(modify);
        imageAdapter = new ImageAdapter(getActivity(), R.layout.item_audio, imageList, this);
        imageAdapter.setModify(modify);
        videoAdapter = new VideoAdapter(getActivity(), R.layout.item_audio, videoList, this);
        videoAdapter.setModify(modify);
        mView.setData(audioAdapter, imageAdapter, videoAdapter);
    }

    private void initData() {
        mView.setText(nodeTaskListBean.getText());
        mView.showScanResult(nodeTaskListBean.isHaveQrCode());
        if (ListUtils.isHaveContent(nodeTaskListBean.getShowImage(cruiseData))) {
            imageList.addAll(nodeTaskListBean.getShowImage(cruiseData));
        }
        if (ListUtils.isHaveContent(nodeTaskListBean.getShowVideo(cruiseData))) {
            videoList.addAll(nodeTaskListBean.getShowVideo(cruiseData));
        }
        if (ListUtils.isHaveContent(nodeTaskListBean.getShowAudio(cruiseData))) {
            audioList.addAll(nodeTaskListBean.getShowAudio(cruiseData));
        }

        switch (editType) {
            case CREATE:
                mView.showDeleteButton(false);
                mView.showSaveButton(true);
                mView.showUploadButton(true);
                break;
            case MODIFY:
                mView.showDeleteButton(true);
                mView.showSaveButton(true);
                mView.showUploadButton(true);
                break;
            case VIEW:
                mView.showDeleteButton(false);
                mView.showSaveButton(false);
                mView.showUploadButton(false);
                break;
        }

    }

    private boolean isHaveContent() {
        return !TextUtils.isEmpty(mView.getText()) || ListUtils.isHaveContent(imageList)
                || ListUtils.isHaveContent(audioList) || ListUtils.isHaveContent(videoList);
    }

    private Activity getActivity() {
        return mView.getActivity();
    }

    @Override
    public void addAudio(String audioPath) {
        audioList.add(audioPath);
        mView.notifyAudiosChange(audioAdapter);
    }

    @Override
    public void reduceAudio(String audioPath) {
        audioList.remove(audioPath);
        mView.notifyAudiosChange(audioAdapter);
        //如果是删除了已上传的数据 则标记为数据已变动
        if (OssManager.isOssUrl(audioPath)) {
            isNetDataChanged = true;
        }
    }

    @Override
    public void addImage(String imagePath) {
        imageList.add(imagePath);
        mView.notifyImagesChange(imageAdapter);
    }

    @Override
    public void reduceImage(String imagePath) {
        imageList.remove(imagePath);
        mView.notifyImagesChange(imageAdapter);
        //如果是删除了已上传的数据 则标记为数据已变动
        if (OssManager.isOssUrl(imagePath)) {
            isNetDataChanged = true;
        }
    }

    @Override
    public void addVideo(String videoPath) {
        videoList.add(videoPath);
        mView.notifyVideosChange(videoAdapter);
    }

    @Override
    public void reduceVideo(String videoPath) {
        videoList.remove(videoPath);
        mView.notifyVideosChange(videoAdapter);
        //如果是删除了已上传的数据 则标记为数据已变动
        if (OssManager.isOssUrl(videoPath)) {
            isNetDataChanged = true;
        }
    }

    @Override
    public void clickOnBack() {
        if (editType == EditType.VIEW || !isDataChanged()) {
            mView.getActivity().finish();
        } else {
            final NormalDialog normalDialog = new NormalDialog(getActivity());
            normalDialog.content("需要保存修改的数据吗?");
            normalDialog.btnText(getActivity().getString(R.string.cancel), getActivity().getString(R.string.templeSave));
            normalDialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {//删除数据
                    normalDialog.dismiss();
                    getActivity().finish();
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {//保存数据
                    normalDialog.dismiss();
                    saveData();
                    mView.showToast("数据已保存");
                    getActivity().finish();

                }
            });
            normalDialog.show();
        }
    }

    /**
     * description:检查页面数据是否有变动
     */
    private boolean isDataChanged() {
        if (cruiseData.isCopyData()) {//本地任务 检查本地数据变动
            return !ListUtils.isStringSame(mView.getText(), nodeTaskListBean.getText())
                    || !ListUtils.isContentSame(imageList, nodeTaskListBean.getOriginalImage())
                    || !ListUtils.isContentSame(videoList, nodeTaskListBean.getOriginalVideos())
                    || !ListUtils.isContentSame(audioList, nodeTaskListBean.getOriginalAudios());
        } else if (cruiseData.isFromNet()) {
            //被驳回的任务 检查本地和已上传的数据变动
            if (isNetDataChanged) {
                return true;
            }
            if (!ListUtils.isStringSame(mView.getText(), nodeTaskListBean.getText())) {
                return true;
            }
            //检查图片
            ArrayList<String> originalImage = new ArrayList<>();
            for (String s : imageList) {
                if (!OssManager.isOssUrl(s)) {
                    originalImage.add(s);
                }
            }
            if (!ListUtils.isContentSame(originalImage, nodeTaskListBean.getOriginalImage())) {
                return true;
            }
            //检查视频
            ArrayList<String> originalVideo = new ArrayList<>();
            for (String s : videoList) {
                if (!OssManager.isOssUrl(s)) {
                    originalVideo.add(s);
                }
            }
            if (!ListUtils.isContentSame(originalVideo, nodeTaskListBean.getOriginalVideos())) {
                return true;
            }
            //检查语音
            ArrayList<String> originalAudio = new ArrayList<>();
            for (String s : audioList) {
                if (!OssManager.isOssUrl(s)) {
                    originalAudio.add(s);
                }
            }
            if (!ListUtils.isContentSame(originalAudio, nodeTaskListBean.getOriginalAudios())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void delete() {
        final NormalDialog normalDialog = new NormalDialog(getActivity());
        normalDialog.content("确定删除本页数据?")
                .btnText("删除", "取消")
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        deleteData();
                        normalDialog.dismiss();
                        mView.showToast(getActivity().getString(R.string.deleted));
                        mView.getActivity().finish();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        normalDialog.dismiss();
                    }
                });
        normalDialog.show();
    }

    private void deleteData() {
        mView.getRealm().executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                nodeTaskListBean.cleanData();
            }
        });
    }

    @Override
    public void clickOnSave() {
        saveData();
        mView.showToast("数据已保存");
        getActivity().finish();
    }

    private void saveData() {
        if (cruiseData.isCopyData()) {//本地任务 直接保存图片等到原数据
            mView.getRealm().executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    if (isDataChanged()) {
                        //设置数据已经变动 在自动上传的时候会用到
//                        cruiseData.setDataChanged(true);
                        //数据变动后 改变上传状态为未上传 需要重新上传
                        nodeTaskListBean.setUploadStatus(0);
                        cruiseData.setUploadStatus(0);
                    }
                    nodeTaskListBean.setText(mView.getText());
                    nodeTaskListBean.setOriginalImage(imageList);
                    nodeTaskListBean.setOriginalVideos(videoList);
                    nodeTaskListBean.setOriginalAudios(audioList);
                }
            });
        } else if (cruiseData.isFromNet()) {//来自服务器的任务 图片等分开存储
            //过滤图片
            final ArrayList<String> netImage = new ArrayList<>();
            final ArrayList<String> originalImage = new ArrayList<>();
            if (ListUtils.isHaveContent(imageList)) {
                for (String s : imageList) {
                    if (OssManager.isOssUrl(s)) {
                        netImage.add(s);
                    } else {
                        originalImage.add(s);
                    }
                }
            }
            //过滤视频
            final ArrayList<String> netVideo = new ArrayList<>();
            final ArrayList<String> originalVideo = new ArrayList<>();
            if (ListUtils.isHaveContent(videoList)) {
                for (String s : videoList) {
                    if (OssManager.isOssUrl(s)) {
                        netVideo.add(s);
                    } else {
                        originalVideo.add(s);
                    }
                }
            }
            //过滤音频
            final ArrayList<String> netAudio = new ArrayList<>();
            final ArrayList<String> originalAudio = new ArrayList<>();
            if (ListUtils.isHaveContent(audioList)) {
                for (String s : audioList) {
                    if (OssManager.isOssUrl(s)) {
                        netAudio.add(s);
                    } else {
                        originalAudio.add(s);
                    }
                }
            }
            mView.getRealm().executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    if (isDataChanged()) {
                        //设置数据已经变动 在自动上传的时候会用到
                        cruiseData.setDataChanged(true);
                        //数据变动后 改变上传状态为未上传 需要重新上传
                        nodeTaskListBean.setUploadStatus(0);
                        cruiseData.setUploadStatus(0);
                    }
                    nodeTaskListBean.setOriginalImage(originalImage);
                    nodeTaskListBean.refreshUploadedImage(netImage);
                    nodeTaskListBean.setOriginalVideos(originalVideo);
                    nodeTaskListBean.refreshUploadedVideo(netVideo);
                    nodeTaskListBean.setOriginalAudios(originalAudio);
                    nodeTaskListBean.refreshUploadedAudio(netAudio);
                    nodeTaskListBean.setText(mView.getText());
                }
            });
        }

    }

    private void setQrCode(final String qrCode) {
        mView.getRealm().executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                nodeTaskListBean.setQrCode(qrCode);
            }
        });
        mView.showScanResult(true);
    }

    @Override
    public void clickOnUpload() {

        saveData();

        if (!nodeTaskListBean.checkContent(cruiseData)) {//信息不完善的时候提示警告用户
            StringBuilder stringBuilder = new StringBuilder("该节点需要提交的信息有:\n");
            if (nodeTaskListBean.isNeedText()) {
                stringBuilder.append("文字");
            }
            if (nodeTaskListBean.isNeedPicture()) {
                stringBuilder.append(" 照片");
            }
            if (nodeTaskListBean.isNeedVideo()) {
                stringBuilder.append(" 视频");
            }
            if (nodeTaskListBean.isNeedAudio()) {
                stringBuilder.append(" 音频");
            }
            if (nodeTaskListBean.isNeedScan()) {
                stringBuilder.append(" 扫码");
            }
            stringBuilder.append("\n是否继续上传?");

            final NormalDialog normalDialog = new NormalDialog(getActivity());
            normalDialog.title("信息不完善")
                    .content(stringBuilder.toString());
            normalDialog.btnText("上传", "继续完善");
            normalDialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    checkNetAndUpload();
                    normalDialog.dismiss();
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    normalDialog.dismiss();
                }
            });
            normalDialog.show();
            return;
        }

        checkNetAndUpload();
    }

    private void checkNetAndUpload() {
        if (NetStatusUtils.isConnected(getActivity())) {
            if (NetStatusUtils.isWifi(getActivity())) {//wifi环境下 全部上传
                uploadData(true);
            } else {//不是WiFi的时候 如果有大文件要上传 提醒用户 让其选择
                if (nodeTaskListBean.isHaveBigLocalFile()) {
                    final NormalDialog normalDialog = new NormalDialog(getActivity());
                    normalDialog.content("当前使用的是数据流量,上传全部文件会消耗较多流量,是否仅上传概要数据?")
                            .btnText("上传全部数据", "上传概要数据")
                            .setOnBtnClickL(new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    uploadData(true);
                                    normalDialog.dismiss();
                                }
                            }, new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    uploadData(false);
                                    normalDialog.dismiss();
                                }
                            });
                    normalDialog.show();
                } else {
                    uploadData(true);
                }
            }
        } else {
            mView.showToast("网络异常,请检查网络状况");
        }
    }

    private void uploadData(boolean all) {
        NodeUpload nodeUpload = new NodeUpload(cruiseData, mView, nodeTaskListBean);
        BaseCallBack baseCallBack = new SimpleCallBack(mView) {
            @Override
            public void onSuccess(Result result) {
                mView.showToast("上传成功");
                getActivity().finish();
            }
        };
        if (all) {
            nodeUpload.uploadOneNodeAllData(baseCallBack);
        } else {
            nodeUpload.uploadOneNodeSimpleData(baseCallBack);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case IntentUtils.AUDIO_RECORD:
                if (data != null) {
                    String path = data.getStringExtra(IntentUtils.DATA);
                    if (path != null) {
                        addAudio(path);
                    }
                }
                break;
            case IntentUtils.TAKE_PICTURE:
                addImage(currentImagePath);
                break;
            case IntentUtils.PICK_PICTURE:
                if (data.getData() != null) {
                    addImage(IntentUtils.getRealFilePath(mView.getActivity(), data.getData()));
                }
                break;
            case PictureConfig.CHOOSE_REQUEST:
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                if (ListUtils.isHaveContent(selectList)) {
                    for (LocalMedia localMedia : selectList) {
                        imageList.add(localMedia.getPath());
                    }
                    mView.notifyImagesChange(imageAdapter);
                }
                break;
            case IntentUtils.TAKE_VIDEO:
                addVideo(currentVideoPath);
                break;
            case IntentUtils.PICK_VIDEO:
                if (data.getData() != null) {
                    addVideo(IntentUtils.getRealFilePath(mView.getActivity(), data.getData()));
                }
                break;
            case IntentUtils.SCAN_QR_CODE:
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    mView.showToast("返回结果为空");
                    return;
                }
                String scanResult = bundle.getString("result");
                setQrCode(scanResult);
                break;
        }
    }

    @Override
    public void openAudioRecord() {
        if (audioList.size() >= 6) {
            mView.showToast(getActivity().getString(R.string.audioLimit));
            return;
        }
        AudioRecordActivity.start(getActivity());
    }

    @Override
    public void openCamera() {
        if (imageList.size() >= 6) {
            mView.showToast(getActivity().getString(R.string.imageLimit));
            return;
        }
        final NormalListDialog normalListDialog = new NormalListDialog(getActivity(), new String[]{"拍照", "从本地选择"});
        normalListDialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        currentImagePath = FileUtils.getNewImagePath();
                        IntentUtils.takePhoto(getActivity(), Uri.fromFile(new File(currentImagePath)));
                        break;
                    case 1:
//                        IntentUtils.pickPhoto(mView.getActivity());
                        PictureSelector.create(mView.getActivity())
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(6 - imageList.size())
                                .compress(false)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                }
                normalListDialog.dismiss();
            }
        });
        normalListDialog.show();
    }

    @Override
    public void openVideo() {
        if (videoList.size() >= 3) {
            mView.showToast(getActivity().getString(R.string.videoLimit));
            return;
        }
        final NormalListDialog normalListDialog = new NormalListDialog(getActivity(), new String[]{"录制视频", "从本地选择"});
        normalListDialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        currentVideoPath = FileUtils.getNewVideoPath();
                        IntentUtils.takeVideo(getActivity(), Uri.fromFile(new File(currentVideoPath)));
                        break;
                    case 1:
                        IntentUtils.pickVideo(mView.getActivity());
                        break;
                }
                normalListDialog.dismiss();
            }
        });
        normalListDialog.show();
    }

    @Override
    public void openScan() {
        IntentUtils.scanQR(mView.getActivity());
    }

}
